//******************************************************************
//******************************************************************
//**********          ANts Peer To Peer Sources        *************
//
// ANts P2P realizes a third generation P2P net. It protects your
// privacy while you are connected and makes you not trackable, hiding
// your identity (ip) and crypting everything you are sending/receiving
// from others.

// Copyright (C) 2004  Roberto Rossi

// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

package ants.p2p.gui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;

import ants.p2p.query.*;
import ants.p2p.utils.indexer.*;

public class QueryResultTable extends JTable {
	QueryAntPanel caller = null;

	static int[] columnSizes = { 500, 50, 50, 120, 200, 500, 230 };

	public QueryResultTable(TableModel model, QueryAntPanel caller) {
		super(model);
		this.caller = caller;

		this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		this.setGridColor(new java.awt.Color(0, 0, 0, 0));

		TableColumnModel columnModel = this.getColumnModel();
		columnModel.getColumn(0).setCellRenderer(
				new FileNameCellRenderer(model));

		try {
			jbInit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void jbInit() throws Exception {
		setFont(new java.awt.Font("Monospaced", 0, 11));
		this.addMouseListener(new QueryResultTable_this_mouseAdapter(this));
	}

	void this_mousePressed(MouseEvent e) {
		if (e.getClickCount() == 1
				&& (e.getButton() == MouseEvent.BUTTON3 || (e.getButton() == MouseEvent.BUTTON1 && e
						.isControlDown()))) {
			int selectedRow = this.getSelectedRow();
			if (selectedRow >= 0) {
				TableSorter sorter = (TableSorter) this.getModel();
				QueryTableModel queryModel = (QueryTableModel) sorter
						.getTableModel();
				FileTupleGroup fileToDownload = (FileTupleGroup) queryModel
						.getResultSet().get(sorter.modelIndex(selectedRow));
				if (fileToDownload.tuples.size() > 0) {
					QueryFileTuple[] sources = new QueryFileTuple[fileToDownload.tuples
							.size()];
					for (int x = 0; x < sources.length; x++) {
						sources[x] = (QueryFileTuple) fileToDownload.tuples
								.get(x);
					}
					AntPopupMenu popup = new AntPopupMenu(this.caller,
							(QueryFileTuple) fileToDownload.tuples.get(0),
							sources);
					popup.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		}
	}

	public long getFileSizeByHash(String sId) {
		TableSorter sorter = (TableSorter) this.getModel();
		QueryTableModel queryModel = (QueryTableModel) sorter.getTableModel();
		FileTupleGroup fileToDownload = (FileTupleGroup) queryModel
				.findByHash(sId);
		// if not found or no source
		if (fileToDownload == null || fileToDownload.tuples.size() == 0)
			return -1;
		return fileToDownload.getSize().longValue();
	}

	public boolean this_mousePressed_by_webgui(String sId) {
		TableSorter sorter = (TableSorter) this.getModel();
		QueryTableModel queryModel = (QueryTableModel) sorter.getTableModel();
		FileTupleGroup fileToDownload = (FileTupleGroup) queryModel
				.findByHash(sId);
		// if not found or no source
		if (fileToDownload == null || fileToDownload.tuples.size() == 0)
			return false;
		QueryFileTuple[] sources = new QueryFileTuple[fileToDownload.tuples
				.size()];
		for (int x = 0; x < sources.length; x++) {
			sources[x] = (QueryFileTuple) fileToDownload.tuples.get(x);
		}

		AntPopupMenu popup = new AntPopupMenu(this.caller,
				(QueryFileTuple) fileToDownload.tuples.get(0), sources);
		popup.ajm.mousePressed(null);
		popup.setVisible(false);
		// popup.show(e.getComponent(), e.getX(), e.getY());
		return true;
	}

	public void setModel(TableModel model) {
		super.setModel(model);
	}
}

class QueryResultTable_this_mouseAdapter extends java.awt.event.MouseAdapter {
	QueryResultTable adaptee;

	QueryResultTable_this_mouseAdapter(QueryResultTable adaptee) {
		this.adaptee = adaptee;
	}

	public void mousePressed(MouseEvent e) {
		adaptee.this_mousePressed(e);
	}
}

class ColumnResizeListener implements TableColumnModelListener {
	QueryResultTable table;

	public ColumnResizeListener(QueryResultTable table) {
		this.table = table;
	}

	public void columnAdded(TableColumnModelEvent e) {
	}

	public void columnMarginChanged(ChangeEvent e) {
		TableColumn column = null;
		for (int i = 0; i < table.getModel().getColumnCount(); i++) {
			column = table.getColumnModel().getColumn(i);
			QueryResultTable.columnSizes[i] = column.getWidth();
		}
	}

	public void columnMoved(TableColumnModelEvent e) {
	}

	public void columnRemoved(TableColumnModelEvent e) {
	}

	public void columnSelectionChanged(ListSelectionEvent e) {
	}
}

class FileNameCellRenderer extends DefaultTableCellRenderer {
	TableModel model;

	public FileNameCellRenderer(TableModel model) {
		this.model = model;
	}

	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		java.awt.Component comp = super.getTableCellRendererComponent(table,
				value, isSelected, hasFocus, row, column);
		comp.setFont(new java.awt.Font("Monospaced", 0, 11));
		if (BackgroundEngine.getInstance().getLocalFile(
				(String) model.getValueAt(row, 6), QueryHashItem.ANTS_HASH) != null) {
			comp.setForeground(Color.blue);
		} else if (BackgroundEngine.getInstance().getPartialFile(
				(String) model.getValueAt(row, 6), QueryHashItem.ANTS_HASH) != null) {
			comp.setForeground(new Color(50, 120, 160));
		} else if (((FileSource) model.getValueAt(row, 1)).getSourceNumber() == 0) {
			long timeSlice = System.currentTimeMillis()
					- ((FileSource) model.getValueAt(row, 1)).getLastTimeSeen();
			if (timeSlice > BackgroundEngine.remoteIndexedDocumentsTimeout) {
				comp.setForeground(new Color(255, 0, 0));
			} else if (timeSlice > 0) {
				int color = (int) Math.floor(timeSlice * 255.0
						/ (60 * 60 * 1000));
				comp.setForeground(new Color(color, 0, 0));
			} else {
				comp.setForeground(new Color(0, 0, 0));
			}
		} else {
			comp.setForeground(new Color(0, 0, 0));
		}
		return comp;
	}
}
